package com.liwei.formatter;

import com.liwei.exception.MyDateException;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public class MyDateFormatter implements Formatter<LocalDate> {
    private String datePattern;
    private String errorMsg;

    public MyDateFormatter(String datePattern, String errorMsg) {
        this.datePattern = datePattern;
        this.errorMsg = errorMsg;
    }

    @Override
    public LocalDate parse(String text, Locale locale) throws ParseException {
        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(datePattern);
        LocalDate parse=null;
        try {
            parse=LocalDate.parse(text,dateTimeFormatter);
        } catch (DateTimeParseException e) {
            throw new MyDateException(errorMsg);
        }
        return parse;
    }

    @Override
    public String print(LocalDate object, Locale locale) {
        String strTemp=object.format(DateTimeFormatter.ofPattern(datePattern));
        return strTemp;
    }
}
